class Resources
{
    constructor(options)
    {
        if (options.url) {
            options.host = options.url;
        }
        this.jira = new JiraClient(options);
        this.customGroup = '';
        this.thead = '<thead class="sc-dxgOiQ iqBXYO" data-testid="tokens-table--head"><tr><th class="sc-ckVGcZ eGnYIS" data-testid="tokens-table--head--cell" tabindex="0"><span>Name</span></th><th class="sc-ckVGcZ eGnYIS" data-testid="tokens-table--head--cell" tabindex="0"><span>Days</span></th><th class="sc-ckVGcZ eGnYIS" data-testid="tokens-table--head--cell" tabindex="0"><span>Total Task</span></th><th class="sc-ckVGcZ eGnYIS" data-testid="tokens-table--head--cell" tabindex="0"><span>New</span></th><th class="sc-ckVGcZ eGnYIS" data-testid="tokens-table--head--cell" tabindex="0"><span>To Do</span></th><th class="sc-ckVGcZ eGnYIS" data-testid="tokens-table--head--cell" tabindex="0"><span>Details</span></th></tr></thead>';
     }

    /**
     *
     * @param string fixVersion
     * @returns array
     */
    async getCurrentData(fixVersion)
    {
        let jql = 'type in (Bug, Task) AND fixVersion = ' + fixVersion + ' ORDER BY assignee ASC, status DESC';
        let issues = [];
        let respPromise = await this.jira.search(jql, {size: 200})
                .then(resp => resp.json())
                .then(resp => {
                    if (resp.total) {
                        issues = resp.issues;
                    }
                });
        return issues;
    }

    async collectResourceData(fixVersion)
    {
        // if has cache
        let cacheKey = 'resources-data-' + fixVersion.split('.').join('_');
        if (localStorage.getItem(cacheKey)?.length) {
            return JSON.parse(localStorage.getItem(cacheKey));
        }

        let self = this;
        let issues = await this.getCurrentData(fixVersion);
        let data = {};
        if (issues.length) {
            issues.forEach((issue, idx) => {
                // name or displayName
              	let uname = 'none';
              	let uemail = 'none';
              	let key = 'unassign';

                if (exclude.uname) {
                    return;
                }

              	if (Object.prototype.toString.call(issue.fields.assignee) != '[object Null]') {
                    uname = issue.fields.assignee?.displayName;
                    uemail = issue.fields.assignee.email;
                    key = uname;
                }
                if (!data[key]) {
                    data[key] = {
                        user: {
                            name: uname,
                            email: uemail
                        },
                        done: 0,
                        process: 0,
                        new: 0,
                        items: []
                    };
                }

                let status = issue.fields.status.name;
                issue.fields.labels.forEach(label => {
                    if (label.toLocaleUpperCase() == 'WOC') {
                        if (status.toLocaleUpperCase()!='DONE') {
                            status = 'WOC';
                        }
                    }
                    if (label.toLocaleUpperCase() == 'RC') {
                         status = 'RC';
                    }
                });

                if (status == 'RC') {
                    return;
                }

                let fixVersions = new Array();
                issue.fields.fixVersions.forEach(version => {
                    fixVersions.push(version.name);
                });

                let regex = /^HPST-\d+/;
                let tmp = issue.fields.summary.match(regex);
                let sourceKey = (tmp==null) ? '' : tmp[0];
                let item = {
                    id: issue.id,
                    key: issue.key,
                    ticket: sourceKey, //issue.fields.customfield_10700,
                    summary: issue.fields.summary,
                    status: status,
                    labels: issue.fields.labels,
                    fixVersion: fixVersions
                };

                if (tmp==null) {
                    console.log('##issue null:', issue);
                } else {
                    console.log('##issue', issue);
                }
                

                if (item.status.toLocaleUpperCase()=='DONE' ||
                    item.status.toLocaleUpperCase()=='QA VERIFICATION' ||
                    item.status.toLocaleUpperCase()=='UNDER REVIEW' ||
                    item.status.toLocaleUpperCase()=='WOC'
                   ) {
                    data[key].done++;
                } else {
                    data[key].process++;
                }
                if (issue.fields.fixVersions.length) {
                    if (issue.fields.fixVersions.length==1 && issue.fields.fixVersions[0].name==fixVersion) {
                         data[key].new = data[key].new + 1;
                    }
                }

                data[key].items.push(item);
            });
        }
      	console.log('##resources list', data);

        if (Object.keys(data).length) {
            // add data cache
            let cacheKey = 'resources-data-' + fixVersion.split('.').join('_');
            localStorage.setItem(cacheKey , JSON.stringify(data));
        }

        return data;
    }

    getFixVersion()
    {
        return localStorage.getItem('fix-version');
    }

    setFixVersion(fixVersion)
    {
        localStorage.setItem('fix-version', fixVersion);
        return this;
    }

    renderAsCustomGroup(items)
    {
        let self = this;
        let tbody = '';
        let details = '<a href="javascript:void()" class="user-tickets-detail">View</a>';

        // group struct
        // {"G1":{"NAME":proportion, "NAME2":proportion}, "G2": {"NAME":proportion, "NAME2":proportion}}
        let groups = Object.keys(this.customGroup);
        groups.forEach((group, idx) => {
            // set group title
            let tasks = '';
            // antiquewhite
            tbody += '<tr class="sc-gqjmRU hReTpu" data-testid="tokens-table--row-row-sync-13" style="background-color:aliceblue;"><td colspan="6" class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-0">' + group + '</td></tr>';
            let groupItems = self.customGroup[group];
            Object.keys(groupItems).forEach((key, _idx) => {
                tasks = '';
                let item = items[key];
                if (!item) {
                    if (groupItems[key]*5) {
                        let row = '<tr class="sc-gqjmRU hReTpu" data-testid="tokens-table--row-row-sync-13"><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-0" style="background-color: antiquewhite;">{name}</td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-0">{time}</td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-1">{totalTask}</td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-2"><div class="sc-kEYyzF Tnalv"><span class="date-text" style="color: green;">{new}</span> </div></td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-2"><div class="sc-kEYyzF Tnalv"><span class="date-text">{process}</span> </div></td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-3">{details}</td></tr>';
                        row = row.replace('{name}', key);
                        row = row.replace('{totalTask}', 0);
                        row = row.replace('{new}', 0);
                        row = row.replace('{process}', 0);
                        row = row.replace('{time}', groupItems[key]*5);
                        row = row.replace('{details}', details + '<ul style="border: 1px solid pink; list-style: inside; display: none;">' + tasks + '</ul>');
                        tbody = tbody + row;
                    }
                    console.log("User", item);
                    console.log('Items', items);
                    //return;
                } else if(item && groupItems[key]*5) {
                    delete items[key];
                    let row = '<tr class="sc-gqjmRU hReTpu" data-testid="tokens-table--row-row-sync-13"><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-0">{name}</td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-0"style="background-color: aliceblue;" >{time}</td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-1">{totalTask}</td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-2"><div class="sc-kEYyzF Tnalv"><span class="date-text" style="color: green;">{new}</span> </div></td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-2"><div class="sc-kEYyzF Tnalv"><span class="date-text">{process}</span> </div></td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-3">{details}</td></tr>';
                    row = row.replace('{name}', item.user.name);
                    row = row.replace('{totalTask}', item.items.length);
                    row = row.replace('{new}', item.new);
                    row = row.replace('{process}', item.process);
                    row = row.replace('{time}', groupItems[key]*5);
                    // items sort
                    item.items.sort((a, b) => {
                        return a.fixVersion.length - b.fixVersion.length;
                    });

                    // get details
                    let color = 'black';
                    item.items.forEach((row,i) => {
                        switch(row.status.toLocaleUpperCase()) {
                            case 'DONE':
                            case 'WOC':
                                color = 'green';
                                break;
                            case 'QA VERIFICATION':
                            case 'UNDER REVIEW':
                                //color = 'blue';
                                color = 'green';
                                break;
                            default:
                                color = 'blue';
                                break;
                        }
                        tasks += '<li><span style="color:' + color + '">' + row.status + '</span> - <span title="' + row.fixVersion.join(',') + '">(fv:' + row.fixVersion.length + ')</span> - <a href="/browse/' + row.ticket + '" target="_bank">' + row.summary + '</a></li>';
                    });
                    row = row.replace('{details}', details + '<ul style="border: 1px solid pink; list-style: inside; display: none;">' + tasks + '</ul>');
                    tbody = tbody + row;
                }
            });
        });

        tbody += '<tr class="sc-gqjmRU hReTpu" data-testid="tokens-table--row-row-sync-13" style="background-color:aliceblue;"><td colspan="6" class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-0">Not in Group</td></tr>';

        tbody += self.defaultTbodyRender(items);

        return tbody;
    }

    defaultTbodyRender(items)
    {
        let details = '<a href="javascript:void()" class="user-tickets-detail">View</a>';
      	let keys = Object.keys(items);
        let tbody = '';
        if (keys.length) {
            keys.forEach((key, idx) => {
                let item = items[key];
                let row = '<tr class="sc-gqjmRU hReTpu" data-testid="tokens-table--row-row-sync-13"><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-0">{name}</td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-0">{time}</td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-1">{totalTask}</td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-2"><div class="sc-kEYyzF Tnalv"><span class="date-text">{done}</span> </div></td><td class="sc-gZMcBi jMyXKQ" data-testid="tokens-table--cell-3">{details}</td></tr>';
                row = row.replace('{name}', item.user.name);
                row = row.replace('{totalTask}', item.items.length);
                row = row.replace('{done}', item.done);
                row = row.replace('{time}', '');
                // items sort

                // get details
                let tasks = '';
                let color = 'black';
                item.items.forEach((row,i) => {
                    switch(row.status.toLocaleUpperCase()) {
                        case 'DONE':
                        case 'WOC':
                            color = 'green';
                        break;
                        case 'QA VERIFICATION':
                        case 'UNDER REVIEW':
                            //color = 'blue';
                            color = 'green';
                        break;
                        default:
                            color = 'blue';
                        break;
                    }
                    tasks += '<li><span style="color:' + color + '">' + row.status + '</span> - <a href="/browse/' + row.ticket + '" target="_bank">' + row.summary + '</a></li>';
                });
                row = row.replace('{details}', details + '<ul style="border: 1px solid pink; list-style: inside; display: none;">' + tasks + '</ul>');
                tbody = tbody + row;
            });
            tbody = '<tbody>' + tbody + '</tbody>';
        }

        return tbody;
    }

    async renderLayout(fixVersion)
    {
        let self = this;
		console.log('##fixVeresion', fixVersion);
        let html = `
        <section id="create-issue-dialog" class="aui-dialog2 aui-layer jira-dialog2 jira-dialog-core aui-dialog2-large jira-dialog-open jira-dialog-content-ready" role="dialog" aria-labelledby="jira-dialog2__heading" style="z-index: 3000;" data-aui-focus="false" data-aui-blanketed="true" open="" tabindex="-1">
        <header class="aui-dialog2-header jira-dialog-core-heading">
        <h2 id="jira-dialog2__heading" title="Create Issue">{fixVersion}&nbsp;&nbsp;<a id="edit-fixversion" href="javascript:void(0)">Edit</a><div style="display:none;"><input id="input-fixversion" placeholder="Input FixVersion" /><button id="update-fixversion-cache">Update</button></div></h2>
        <span id="resources-close" style="padding: 5px 10px;font-weight: bold;border: 1px dashed darkslategrey;cursor: pointer;">X</span>
        </header>
        <div class="aui-dialog2-content jira-dialog-core-content">
        <div class="qf-container">
        <div class="form-footer">
        <div class="dialog-error">
        {table}
        </div>
        </div>
        </div>
        </div>
        <footer class="aui-dialog2-footer">
        <div class="buttons-container form-footer">
        <div class="buttons">
        <span class="throbber"></span>
        <button class="aui-button aui-button-link cancel" id="aui-dialog-close" resolved="">Close</button>
        </div></div></footer></section>
        <div id="jira-bg-mark" aria-hidden="true" class="aui-blanket" tabindex="0" style="z-index: 2980;"></div>
`;
        html = html.replace('{fixVersion}', fixVersion);

        let table = '<div class="sc-kkGfuU cFzHhH"><div class="sc-jzJRlG cjiXFR"><table class="issue-table" data-testid="tokens-table--table">{thead}{tbody}</table></div></div>';
        let thead = this.thead;
        let tbody = '';

        let items = {};
        if (self.getFixVersion()) {
            // get all user
            items = await self.collectResourceData(fixVersion);
        }

        if (self.customGroup) {
            tbody = self.renderAsCustomGroup(items);
        } else {
            tbody = self.defaultTbodyRender(items);
        }

        table = table.replace('{thead}', thead);
        table = table.replace('{tbody}', tbody);
        html = html.replace('{table}', table);

        jQuery('body').append(html);
        jQuery('#update-fixversion-cache').on('click', function(){
            self.setFixVersion(jQuery('#input-fixversion').val());
            jQuery('#jira-bg-mark').remove();
            jQuery('#create-issue-dialog').remove();
            jQuery('#fetch-resource').trigger('click');
        });
        jQuery('.aui-blanket').on('click', function() {
            jQuery('#jira-bg-mark').remove();
            jQuery('#create-issue-dialog').remove();
        });
        jQuery('#aui-dialog-close').on('click', function() {
            jQuery('#jira-bg-mark').remove();
            jQuery('#create-issue-dialog').remove();
        });
        jQuery('#resources-close').on('click', function() {
            jQuery('#jira-bg-mark').remove();
            jQuery('#create-issue-dialog').remove();
        });
        jQuery('.user-tickets-detail').toggle(function(){
            jQuery('#details-' + jQuery(this).parent().parent().index()).remove();
            jQuery(this).parent().parent().after('<tr id="details-' +  jQuery(this).parent().parent().index() + '"><td colspan="4"><ul style="border: 1px pink solid;padding: 5px;">' + jQuery(this).next().html() + '</ul></td></tr>');
        }, function(){
            jQuery('#details-' + jQuery(this).parent().parent().index()).remove();
        });
        jQuery('#edit-fixversion').on('click', function() {
            jQuery(this).toggle().next().toggle();
        });
    }

    init()
    {
        let self = this;
        jQuery('.aui-header-primary ul.aui-nav').append('<li><button id="fetch-resource">Resources</button></li>');
        jQuery('#fetch-resource').on('click', function() {
            self.renderLayout(self.getFixVersion());
        });
    }
}
var exclude = {};

var resourcesObj = new Resources(JSON.parse(localStorage.getItem('config')).target);
//var data = await resourcesObj.collectResourceData('v1.23.0221');
resourcesObj.init();
// resourcesObj.customGroup = {
//     "Group A": {
//         "Test A": 0.6
//     },
//     "Group B": {
//         "Test B": 0,
//     }
// }